#include "Team.h"
#include "ui_Team.h"
#include "Manage.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include <QBitmap>
#include <QStyleOption>
#include <QMouseEvent>
#include <QPainter>
#include "mymessagebox.h"

Team::Team(Manage *manage,QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Team)
    , manageWindow(manage)
{
    ui->setupUi(this);

    // 隐藏原生标题栏
    setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);

    // 防止窗口背景透明
    setAttribute(Qt::WA_TranslucentBackground, false);

    // 定义要显示的日期
    QStringList days = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};

    // 添加带复选框的 QListWidgetItem
    for (const QString &day : days) {
        QListWidgetItem *item = new QListWidgetItem(day, ui->date);
        item->setCheckState(Qt::Unchecked);  // 设置复选框为未选中状态
    }

    // 加载员工信息
    loadEmployeeInfo();
}

Team::~Team()
{
    delete ui;
}

// 实现窗口拖动功能
void Team::mousePressEvent(QMouseEvent *event)
{
    // 检查是否点击了自定义标题栏
    if (event->button() == Qt::LeftButton && event->pos().y() <= 60) {
        m_isTitleBarClicked = true;
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    } else {
        m_isTitleBarClicked = false;
        // 让事件继续传播，确保其他控件能响应点击事件
        QWidget::mousePressEvent(event);
    }
}

void Team::mouseMoveEvent(QMouseEvent *event)
{
    // 只有在点击了标题栏之后才允许拖动
    if (m_isTitleBarClicked && (event->buttons() & Qt::LeftButton)) {
        move(event->globalPos() - m_dragPosition);
        event->accept();
    } else {
        // 让事件继续传播，确保其他控件能响应移动事件
        QWidget::mouseMoveEvent(event);
    }
}

void Team::paintEvent(QPaintEvent *event)
{
    // 1. 绘制样式（QSS）
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); // 绘制样式

    // 2. 设置掩码，约定 painter 绘制区域
    QBitmap bmp(this->size());
    bmp.fill(Qt::white); // 填充 bitmap

    QPainter painter(&bmp);
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black); // 掩码值
    painter.drawRoundedRect(bmp.rect(), 30, 30); // 在 bitmap 中绘制圆角矩形

    // 设置掩码以确定本控件可绘制区域
    setMask(bmp);

    // 调用基类的 paintEvent
    QWidget::paintEvent(event);
}

void Team::loadEmployeeInfo()
{
    QSqlQuery query;
    query.prepare("SELECT 工号, 姓名, 标签号 FROM EmployeeInfo");  // 查询标签号

    if (query.exec()) {
        while (query.next()) {
            int tagNumber = query.value(2).toInt();  // 获取标签号

            if (tagNumber != 0) {  // 判断标签号不为0
                QString employee = query.value(0).toString() + "-" + query.value(1).toString();
                QListWidgetItem *item = new QListWidgetItem(employee, ui->namelist);
                item->setCheckState(Qt::Unchecked);  // 设置复选框为未选中
            }
        }
    } else {
        // QMessageBox::critical(this, "错误", "无法加载员工信息: " + query.lastError().text());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法加载员工信息: " + query.lastError().text());
        msgBox.setButton("确定");
        msgBox.exec();
    }
}

QList<QString> Team::getSelectedEmployees()
{
    QList<QString> selectedEmployees;
    for (int i = 0; i < ui->namelist->count(); ++i) {
        QListWidgetItem *item = ui->namelist->item(i);
        if (item->checkState() == Qt::Checked) {
            selectedEmployees.append(item->text());
        }
    }
    return selectedEmployees;
}

QString Team::getSelectedAttendanceDays()
{
    QString attendanceDays = "0000000";
    for (int i = 0; i < ui->date->count(); ++i) {
        QListWidgetItem *item = ui->date->item(i);
        if (item->checkState() == Qt::Checked) {
            attendanceDays[i] = '1';
        }
    }
    return attendanceDays;
}

void Team::on_returnButton_clicked()
{
    this->close();
    manageWindow->refreshPageData();
    manageWindow->show();
}


void Team::on_no_clicked()
{
    this->close();
    manageWindow->refreshPageData();
    manageWindow->show();
}


void Team::on_yes_clicked()
{
    int groupNumber = ui->num->text().toInt();
    QTime startTime = ui->start->time();
    QTime endTime = ui->end->time();

    // 获取选中的员工
    QList<QString> selectedEmployees = getSelectedEmployees();
    if (selectedEmployees.isEmpty()) {
        // QMessageBox::warning(this, "警告", "未选择员工");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("警告");
        msgBox.setText("未选择员工");
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    // 获取选中的考勤日期
    QString selectedDays = getSelectedAttendanceDays();
    if (selectedDays == "0000000") {
        // QMessageBox::warning(this, "警告", "未选择考勤日期");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("警告");
        msgBox.setText("未选择考勤日期");
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    // 检查打卡时间
    if (endTime <= startTime) {
        // QMessageBox::warning(this, "警告", "打卡时间错误");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("警告");
        msgBox.setText("打卡时间错误");
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    // 检查考勤组号是否为空
    if (ui->num->text().isEmpty()) {
        // QMessageBox::warning(this, "警告", "考勤组号为空");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("警告");
        msgBox.setText("考勤组号为空");
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    // 检查考勤组号是否存在
    QSqlQuery query;
    query.prepare("SELECT 考勤组号 FROM AttendanceGroup WHERE 考勤组号 = :groupNumber");
    query.bindValue(":groupNumber", groupNumber);
    if (query.exec() && query.next()) {
        // QMessageBox::warning(this, "警告", "考勤组号已存在");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("警告");
        msgBox.setText("考勤组号已存在");
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    // 插入考勤组数据
    query.prepare("INSERT INTO AttendanceGroup (考勤组号, 开始时间, 结束时间, 考勤日期) "
                  "VALUES (:groupNumber, :startTime, :endTime, :attendanceDays)");
    query.bindValue(":groupNumber", groupNumber);
    query.bindValue(":startTime", startTime);
    query.bindValue(":endTime", endTime);
    query.bindValue(":attendanceDays", selectedDays);

    if (!query.exec()) {
        // QMessageBox::critical(this, "错误", "插入考勤组数据失败: " + query.lastError().text());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("插入考勤组数据失败: " + query.lastError().text());
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    // 动态创建考勤组人员表
    QString tableName = QString("`%1`").arg(groupNumber);
    query.prepare(QString("CREATE TABLE IF NOT EXISTS %1 (工号 INT, 姓名 VARCHAR)").arg(tableName));
    if (!query.exec()) {
        // QMessageBox::critical(this, "错误", "创建考勤组人员表失败: " + query.lastError().text());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("创建考勤组人员表失败: " + query.lastError().text());
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    // 插入选中的员工到考勤组人员表
    for (const QString &employee : selectedEmployees) {
        QStringList employeeData = employee.split("-");
        int employeeId = employeeData[0].toInt();
        QString employeeName = employeeData[1];

        query.prepare(QString("INSERT INTO %1 (工号, 姓名) VALUES (:employeeId, :employeeName)").arg(tableName));
        query.bindValue(":employeeId", employeeId);
        query.bindValue(":employeeName", employeeName);

        if (!query.exec()) {
            // QMessageBox::critical(this, "错误", "插入考勤组人员失败: " + query.lastError().text());
            MyMessageBox msgBox;
            msgBox.setWindowTitle("错误");
            msgBox.setText("插入考勤组人员失败: " + query.lastError().text());
            msgBox.setButton("确定");
            msgBox.exec();
            return;
        }

        // 查找并插入考勤组号到员工个人表
        QString personalTable = QString("`%1_%2`").arg(employeeId).arg(employeeName);
        query.prepare(QString("SELECT 1 FROM %1 LIMIT 1").arg(personalTable));  // 尝试从 personalTable 读取数据
        if (query.exec()) {
            // 如果查询成功，表示表存在，插入考勤组号到员工个人表中
            query.prepare(QString("INSERT INTO %1 (考勤组号) VALUES (:groupNumber)").arg(personalTable));
            query.bindValue(":groupNumber", groupNumber);
            if (!query.exec()) {
                // QMessageBox::critical(this, "错误", "插入考勤组号失败: " + query.lastError().text());
                MyMessageBox msgBox;
                msgBox.setWindowTitle("错误");
                msgBox.setText("插入考勤组号失败: " + query.lastError().text());
                msgBox.setButton("确定");
                msgBox.exec();
                return;
            }
        } else {
            // QMessageBox::critical(this, "错误", "未找到个人表: " + personalTable);
            MyMessageBox msgBox;
            msgBox.setWindowTitle("错误");
            msgBox.setText("未找到个人表: " + personalTable);
            msgBox.setButton("确定");
            msgBox.exec();
            return;
        }
    }

    // 在考勤组及其人员表成功创建后，清空输入数据
    ui->num->clear();  // 清空考勤组号输入框
    ui->start->setTime(QTime(0, 0));  // 清空打卡开始时间
    ui->end->setTime(QTime(0, 0));    // 清空打卡结束时间

    // 清除 namelist 中选中的项
    for (int i = 0; i < ui->namelist->count(); ++i) {
        QListWidgetItem *item = ui->namelist->item(i);
        item->setCheckState(Qt::Unchecked);  // 设置为未选中状态
    }

    // 清除 date 中选中的日期
    for (int i = 0; i < ui->date->count(); ++i) {
        QListWidgetItem *item = ui->date->item(i);
        item->setCheckState(Qt::Unchecked);  // 设置为未选中状态
    }

    // QMessageBox::information(this, "成功", "考勤组及其人员已成功创建");
    MyMessageBox msgBox;
    msgBox.setWindowTitle("成功");
    msgBox.setText("考勤组及其人员已成功创建");
    msgBox.setButton("确定");
    msgBox.exec();
}

